using MediatR;
using RBAC.Api.Demain.ContentManagement;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Read.Command.ContentManagement;

namespace RBAC.Api.Read.CommandHandler.ContentManagement
{
    /// <summary>
    /// 显示医院列表处理器
    /// </summary>
    public class ShowHospitalCommandHandler : IRequestHandler<ShowHospitalCommand, APIResult<APIPagin<HospitalModel>>>
    {
        private readonly IBaseRepositry<HospitalModel> baseRepositry;

        public ShowHospitalCommandHandler(IBaseRepositry<HospitalModel> baseRepositry)
        {
            this.baseRepositry = baseRepositry;
        }

        public Task<APIResult<APIPagin<HospitalModel>>> Handle(ShowHospitalCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPagin<HospitalModel>> result = new APIResult<APIPagin<HospitalModel>>();
            result.Message = "获取医院列表成功";
            result.Code = ResultCode.Success;

            var list = baseRepositry.GetAll();

            // 根据医院名称模糊查询
            if (!string.IsNullOrEmpty(request.Name))
            {
                list = list.Where(x => x.Name.Contains(request.Name));
            }

            // 根据医院地址模糊查询
            if (!string.IsNullOrEmpty(request.Address))
            {
                list = list.Where(x => x.Address.Contains(request.Address));
            }

            var totalCount = list.Count();
            var page = (int)Math.Ceiling((totalCount * 1.0) / request.PageSize);
            list = list.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPagin<HospitalModel> res = new APIPagin<HospitalModel>()
            {
                TotaleCount = totalCount,
                PageCount = page,
                List = list.ToList()
            };

            result.Data = res;

            return Task.FromResult(result);
        }
    }
}